package com.lz.sports.ui.config

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.lz.comm.BR
import com.lz.library.base.BaseFragment
import com.lz.library.extension.click
import com.lz.library.extension.resString
import com.lz.sports.R
import com.lz.sports.bean.DeviceInfo
import com.lz.sports.databinding.FragmDeviceEditBinding
import com.lz.sports.dialog.DelayedLoadingDialog
import com.lz.sports.dialog.WarningDialog
import com.lz.sports.vm.config.DeviceEditViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

//设备编辑
class DeviceEditFragment : BaseFragment<DeviceEditViewModel, FragmDeviceEditBinding>(),
    WarningDialog.OnWarningConfirmListener, MenuDelete {

    companion object {
        const val REQUEST_DELETE = 1
    }

    override fun getLayoutRes(): Int = R.layout.fragm_device_edit

    override fun getVMVariableId(): Int = BR.vm

    override fun initObserve() {
        viewModel.finishEvent.observe(this) { if (it) findNavController().popBackStack() }
        viewModel.delayEvent.observe(this) {
            DelayedLoadingDialog.show(this, it)
        }
    }

    override fun initData(savedState: Bundle?) {
        val position = arguments!!.getInt("position", 0)
        val list = arguments!!.getParcelableArrayList<DeviceInfo>("deviceInfoList")
        viewModel.initDeviceInfoList(list!!, position)

        lifecycleScope.launch {
            arrayOf(
                binding.tvSave,
                binding.tvConnect,
                binding.tvSend,
                binding.tvPre,
                binding.tvNext
            ).click().collect { onClick(it) }
        }
    }

    private fun onClick(v: View) {
        when (v.id) {
            R.id.tv_save -> viewModel.save()
            R.id.tv_connect -> viewModel.connect()
            R.id.tv_send -> viewModel.send()
            R.id.tv_pre -> viewModel.pre()
            R.id.tv_next -> viewModel.next()
        }
    }

    override fun onConfirm(dialog: WarningDialog, requestCode: Int) {
        dialog.dismiss()
        when (requestCode) {
            REQUEST_DELETE -> viewModel.delete()
        }
    }

    override fun delete() {
        WarningDialog.show(this, R.string.device_delete_w.resString(), "", REQUEST_DELETE)
    }
}